package com.qiqv.demo.transformer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * @author hjr
 * @version 1.0
 * @date 2023/12/9 15:40
 */
public class OrderTransformer implements ClassFileTransformer {

    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        if(!className.equals("com/qiqv/controller/OrderController")){
            return classfileBuffer;
        }
        System.out.println("find OrderController class, start to replace");
        byte[] newClassByte = getNewClassBytes();
        return newClassByte;
    }

    private byte[] getNewClassBytes() {
        File file = new File("D:\\devWorkPlace\\devCode\\mime\\java-agent\\web-application-demo\\target\\test-classes\\com\\qiqv\\controller\\OrderController.class");
        try(InputStream is = new FileInputStream(file);
            ByteArrayOutputStream bs = new ByteArrayOutputStream()){
            long length = file.length();
            byte[] bytes = new byte[(int) length];

            int n;
            while ((n = is.read(bytes)) != -1) {
                bs.write(bytes, 0, n);
            }
            return bytes;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
